from datetime import datetime

from flask import Blueprint, render_template, request, flash, redirect, url_for

from decorators import login_required
from exts import db
from models import PurchaseOrderModel, ProductPurchaseOrderModel, ProductModel

bp = Blueprint("purchase_orders", __name__, url_prefix="/purchase_orders")


@bp.route("/", methods=["GET"])
@login_required
def purchase_orders():
    purchase_orders = PurchaseOrderModel.query.all()
    result = []
    for purchase_order in purchase_orders:
        purchase_order_data = {
            "id": purchase_order.id,
            "purchase_time": purchase_order.purchase_time.strftime("%Y-%m-%d %H:%M:%S")
        }
        result.append(purchase_order_data)
    return render_template("采购管理.html",purchase_order=result)

@bp.route("/detail/<int:purchase_order_id>", methods=["GET"])
@login_required
def purchase_orders_detail(purchase_order_id):
    purchase_order = PurchaseOrderModel.query.get(purchase_order_id)
    if not purchase_order:
        return "Purchase order not found", 404

    purchase_order_data = {
        "id": purchase_order.id,
        "purchase_time": purchase_order.purchase_time.strftime("%Y-%m-%d %H:%M:%S")
    }

    products = ProductPurchaseOrderModel.query.filter_by(purchase_orders_id=purchase_order_id).all()
    product_data = []
    for product in products:
        product_item = {
            "name": product.product.name,
            "purchase_quantity": product.purchase_quantity,
            "purchase_price": product.purchase_price,
            "supplier":product.product.supplier
        }
        product_data.append(product_item)

    return render_template("采购订单商品详情.html", purchase_order=purchase_order_data, products=product_data)


@bp.route("/create_purchase_order")
@login_required
def create_purchase_order():
    # 创建新的采购订单
    purchase_order = PurchaseOrderModel(purchase_time=datetime.now())
    db.session.add(purchase_order)
    db.session.commit()
    db.session.flush()  # flush操作是为了获取purchase_order的id
    return  render_template("新增采购订单.html",purchase_order=purchase_order)

@bp.route("/display_purchase_order/<purchase_order_id>")
@login_required
def display_purchase_order(purchase_order_id):
    purchase_order = PurchaseOrderModel.query.get(purchase_order_id)
    if not purchase_order:
        return "Purchase order not found", 404

    purchase_order_data = {
        "id": purchase_order.id,
        "purchase_time": purchase_order.purchase_time.strftime("%Y-%m-%d %H:%M:%S")
    }

    products = ProductPurchaseOrderModel.query.filter_by(purchase_orders_id=purchase_order_id).all()
    product_data = []
    for product in products:
        product_item = {
            "id":product.id,
            "name": product.product.name,
            "purchase_quantity": product.purchase_quantity,
            "purchase_price": product.purchase_price,
            "total_amount":product.total_amount,
            "supplier":product.product.supplier
        }
        product_data.append(product_item)
    return render_template("新增采购订单.html", purchase_order=purchase_order_data, products=product_data)

@bp.route("/add_product/<purchase_order_id>", methods=["POST"])
def add_product(purchase_order_id):
    product_name = request.form['product_name']
    product= ProductModel.query.filter_by(name=product_name).first()
    purchase_price = request.form['purchase_price']
    purchase_quantity = request.form['purchase_quantity']
    new_supplier = request.form['supplier']

    productpurchaseorder = ProductPurchaseOrderModel(purchase_orders_id=purchase_order_id,product_id=product.id,purchase_quantity=purchase_quantity,purchase_price=purchase_price,total_amount=float(purchase_price)*float(purchase_quantity))
    db.session.add(productpurchaseorder)
    db.session.commit()

    return redirect(url_for('purchase_orders.display_purchase_order',purchase_order_id=purchase_order_id))

@bp.route("/manage_product/<productpurchaseorder_id>", methods=["POST"])
def manage_product(productpurchaseorder_id):
    new_product_name = request.form['new_product_name']
    products= ProductModel.query.filter_by(name=new_product_name).first()
    new_price = float(request.form['new_price'])
    new_quantity = int(request.form['new_quantity'])
    new_supplier = request.form['new_supplier']

    product = ProductPurchaseOrderModel.query.get(productpurchaseorder_id)
    if product:
        product.product_id = products.id
        product.purchase_price = new_price
        product.purchase_quantity = new_quantity
        product.total_amount = float(new_price)*float(new_quantity)
        db.session.commit()
        flash('商品信息更新成功', 'success')
    else:
        flash('商品不存在', 'error')

    return redirect(url_for('purchase_orders.display_purchase_order', purchase_order_id=product.purchase_orders_id))


@bp.route("/save_purchase_order/<purchase_order_id>")
@login_required
def save_purchase_order(purchase_order_id):
    purchase_order = PurchaseOrderModel.query.get_or_404(purchase_order_id)
    items = purchase_order.product_purchase_order_relationship

    for item in items:
        product = ProductModel.query.get(item.product_id)
        product.stock_quantity += item.purchase_quantity

    db.session.commit()
    return redirect(url_for('purchase_orders.purchase_orders'))

@bp.route("/cancel_purchase_order/<purchase_order_id>")
def cancel_purchase_order(purchase_order_id):
    purchase_order = PurchaseOrderModel.query.get_or_404(purchase_order_id)
    db.session.delete(purchase_order)
    db.session.commit()
    return redirect(url_for('purchase_orders.purchase_orders'))



@bp.route("/delete_purchase_order",methods=['POST'])
@login_required
def delete_purchase_order():
    purchase_orders_id = request.form['purchase_order_id']

    purchase_orders = PurchaseOrderModel.query.get(purchase_orders_id)
    if purchase_orders:
        db.session.delete(purchase_orders)
        db.session.commit()
        flash('采购订单删除成功', 'success')
    else:
        flash('采购订单不存在', 'error')

    return redirect(url_for('purchase_orders.purchase_orders'))


@bp.route('/search_purchase_orders', methods=['GET'])
@login_required
def search_purchase_orders():
    search_text = request.args.get('search')  # 获取查询字符串中的搜索关键字
    if search_text:
        purchase_orders = PurchaseOrderModel.query.filter(id==search_text).all()
    else:
        purchase_orders = PurchaseOrderModel.query.all()

    result = []
    for purchase_order in purchase_orders:
        purchase_order_data = {
            "id": purchase_order.id,
            "purchase_time": purchase_order.purchase_time.strftime("%Y-%m-%d %H:%M:%S")
        }
        result.append(purchase_order_data)
    return render_template("采购管理.html", purchase_order=result)